package com.aqadoos.service;

import java.util.List;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.aqadoos.domain.Department;

/**
 * User: Ata-ul.Qadoos
 */
@Component
@Transactional
public class DepartmentService {
    
    @PersistenceContext
    private EntityManager em;    
    
    public Long create(Department department) {
        em.persist(department);
        return department.id;
    }

    public Department findById(Long id) {
        return em.find(Department.class, id);
    }

    @SuppressWarnings("unchecked")
	public List<Department> findAll() {
        Query query = em.createQuery("from Department d");
        return (List<Department>) query.getResultList();
    }

    public Department findByName(String departmentName) {
        Query query = em.createQuery("from Department d where d.name=:departmentName");
        query.setParameter("departmentName", departmentName);
        @SuppressWarnings("unchecked")
		List<Department> result = (List<Department>) query.getResultList();
        if(result != null && result.size() > 0) {
            return result.get(0);
        }

        return null;
    }
}
